package com.zdp.剑指offer;

import com.zdp.util.ListNode;

import java.util.ArrayList;

public class 从尾到头打印链表 {
    static int Max= 1000;
    public static void main(String[] args) {
        从尾到头打印链表 demo = new 从尾到头打印链表();
        ListNode p = demo.createList(10);
        demo.outList(p);
        ArrayList<Integer> integers = demo.printListFromTailToHead(p);
        for(Integer i:integers){
            System.out.print(i+",");
        }

    }
    /*public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode p = listNode;
        Stack<Integer> result = new Stack<Integer>();
        while(p!=null){
            result.push(p.val);
            p = p.next;
        }
        ArrayList<Integer> list = new ArrayList();
        while(!result.empty()){
            list.add(result.pop());
        }
        return list;
    }*/
    //使用递归试试
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode p = listNode;
        ArrayList<Integer> list = new ArrayList();
        f(p,list);
        return list;
    }
    public void f(ListNode p,ArrayList<Integer> list){
        if(p==null){
            return ;
        }
        f(p.next,list);
        list.add(p.val);
    }

    //生成测试数据
    public ListNode createList(int length){
        ListNode head = new ListNode((int)(Math.random()*Max));
        ListNode result = head;
        for(int i=0;i<length-1;i++){
            ListNode p = new ListNode((int)(Math.random()*Max));
            head.next = p;
            head = p;
        }
        return result;
    }
    //打印链表
    public void outList(ListNode list){
        while(list!=null){
            if(list.next==null){
                System.out.print(list.val+"\n");
            }else{
                System.out.print(list.val+",");
            }
            list = list.next;
        }
    }
}

